package com.heima.wemedia.service.impl;


import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;

import com.heima.wemedia.service.WmNewsAuditService;
import com.heima.wemedia.service.WmNewsService;

import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {


    @Autowired
    private IScheduleClient scheduleClient;

    @Override
    public void addTask(WmNews wmNews) {
        //1.基于文章封装任务
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());//执行时间：文章的发布时间
        task.setParameters(ProtostuffUtil.serialize(wmNews));//参数数据：文章的字节数组
        task.setTaskType(TaskTypeEnum.WM_NEWS.getTaskType());//任务类型：自媒体文章类型
        task.setPriority(TaskTypeEnum.WM_NEWS.getPriority());//任务优先级：自媒体优先级

        //2.将任务添加到DB任务表和Cache队列中
        scheduleClient.addTask(task);
    }

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    @Lazy
    private WmNewsAuditService wmNewsAuditService;

    /**
     * 定时拉取任务执行文章发布
     */
    @Scheduled(cron = "*/1 * * * * ?")
    @Override
    public void pollTask() {

        //1.拉取任务
        Task task = scheduleClient.pollTask(TaskTypeEnum.WM_NEWS.getTaskType(), TaskTypeEnum.WM_NEWS.getPriority());

        if(task!=null){
            //2.获取任务里的文章对象
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);

            //3.获取文章id
            Integer wmNewsId = wmNews.getId();

            //4.判断文章状态是否处于待发布状态 select count(*) from wm_news where status in (4,8) and id=?
            Integer count = wmNewsService.lambdaQuery()
                    .eq(WmNews::getId, wmNewsId)
                    .in(WmNews::getStatus, WmNews.Status.ADMIN_SUCCESS.getCode(), WmNews.Status.SUCCESS.getCode())
                    .count();

            if(count>0){
                //5.执行文章发布（创建APP文章且修改文章状态为已发布9）
                wmNewsAuditService.doArticlePublish(wmNews);
            }
        }


    }
}
